package com.softeware.dao;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static { init(); }
    public static void init(){
        Properties properties = new Properties();
        try{
            properties.load(BaseDao.class.getClassLoader().getResourceAsStream("database.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver=properties.getProperty("driver");
        url=properties.getProperty("url");
        username=properties.getProperty("username");
        password=properties.getProperty("password");
    }
    public static Connection getConnection() throws SQLException {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){
        boolean flag = true;
        if(rs!=null){
            try{
                rs.close();
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }finally {
                rs=null;
            }
        }
        if(pstm!=null){
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
                flag=false;
            }finally {
                pstm=null;
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }finally {
                connection=null;
            }
        }
        return flag;
    }
    public static ResultSet execute(Connection conn, PreparedStatement pstm, ResultSet rs, String sql, Object[] params) throws SQLException {
        pstm = conn.prepareStatement(sql);
        for(int i = 0;i<params.length;i++){
            pstm.setObject(i+1,params[i]);
        }
        rs = pstm.executeQuery();
        return rs;
    }
    public static int execute(Connection conn, PreparedStatement pstm, String sql, Object[] params) throws SQLException {
        pstm = conn.prepareStatement(sql);
        for(int i=0;i<params.length;i++){
            pstm.setObject(i+1,params[i]);
        }
        int updataRows = pstm.executeUpdate();
        return updataRows;
    }
}
